package com.demo.autotest.service;

import com.demo.autotest.common.exception.DuplicateException;
import com.demo.autotest.database.domain.Operation;
import com.demo.autotest.database.mapper.OperationMapper;
import com.demo.autotest.dto.OperationDTO;
import com.demo.autotest.request.QueryRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

@Service    // 定义service层
@Transactional(rollbackFor = Exception.class)
public class OperationService {

    @Resource
    private OperationMapper operationMapper;

    public void saveOperation(Operation operation){
        Operation old = operationMapper.getOperationByName(operation.getProjectId(), operation.getName(), operation.getSystem());
        if(old != null && !old.getId().equals(operation.getId())){
            throw new DuplicateException("本项目已有该操作名称");
        }
        if(operation.getId() != null && !operation.getId().equals("")){
            operation.setUpdateTime(System.currentTimeMillis());
        }else{
            operation.setId(UUID.randomUUID().toString());
            operation.setCreateUser(operation.getUpdateUser());
            operation.setCreateTime(System.currentTimeMillis());
            operation.setUpdateTime(System.currentTimeMillis());
        }
        operationMapper.saveOperation(operation);
    }

    public void delete(String id){
        operationMapper.delete(id);
    }

    public Operation getOperationDetail(String id){
        return operationMapper.getOperationDetail(id);
    }

    public List<OperationDTO> getOperationList(QueryRequest request){
        if(request.getCondition() != null && !request.getCondition().equals("")){
            request.setCondition("%" + request.getCondition() + "%");
        }
        return operationMapper.getOperationList(request);
    }

}
